import { defineStore } from 'pinia';
import { 
  getPricingPlans, getCurrentSubscription, createSubscription,
  cancelAutoRenew, createPayment, processPayment, getPaymentHistory
} from '../api/subscription';

export const useSubscriptionStore = defineStore('subscription', {
  state: () => ({
    pricingPlans: [],
    currentSubscription: null,
    paymentHistory: [],
    loading: false,
    error: null,
    lastFetchTime: null // 添加最后获取时间，用于缓存控制
  }),
  
  getters: {
    hasActiveSubscription: (state) => {
      return state.currentSubscription && 
             new Date(state.currentSubscription.end_date) > new Date();
    },
    
    subscriptionTier: (state) => {
      if (!state.currentSubscription) return 'free';
      return state.currentSubscription.pricing_plan.tier;
    },
    
    daysRemaining: (state) => {
      if (!state.currentSubscription) return 0;
      const endDate = new Date(state.currentSubscription.end_date);
      const today = new Date();
      const diffTime = endDate - today;
      return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    }
  },
  
  actions: {
    async fetchPricingPlans(forceRefresh = false) {
      // 如果不是强制刷新且数据已存在且在5分钟内，直接返回缓存数据
      if (!forceRefresh && this.pricingPlans.length > 0 && this.lastFetchTime) {
        const now = Date.now();
        const fiveMinutes = 5 * 60 * 1000;
        if (now - this.lastFetchTime < fiveMinutes) {
          return this.pricingPlans;
        }
      }

      this.loading = true;
      try {
        const response = await getPricingPlans();
        // 确保返回的是results数组，如果是分页数据
        const plans = response.results || response;
        this.pricingPlans = plans;
        this.lastFetchTime = Date.now();
        return plans;
      } catch (error) {
        this.error = '获取价格方案失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    async fetchCurrentSubscription(forceRefresh = false) {
      // 如果不是强制刷新且数据已存在且在1分钟内，直接返回缓存数据
      if (!forceRefresh && this.currentSubscription !== null && this.lastFetchTime) {
        const now = Date.now();
        const oneMinute = 60 * 1000;
        if (now - this.lastFetchTime < oneMinute) {
          return this.currentSubscription;
        }
      }

      this.loading = true;
      try {
        const subscription = await getCurrentSubscription();
        this.currentSubscription = subscription;
        this.lastFetchTime = Date.now();
        return subscription;
      } catch (error) {
        if (error === null) {
          // 用户没有活跃订阅
          this.currentSubscription = null;
          this.lastFetchTime = Date.now();
          return null;
        }
        this.error = '获取当前订阅信息失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    async subscribeToNewPlan(planId) {
      this.loading = true;
      try {
        const subscriptionData = {
          pricing_plan: planId,
          auto_renew: true
        };
        const subscription = await createSubscription(subscriptionData);
        
        // 创建支付记录
        const paymentData = {
          subscription: subscription.id,
          amount: subscription.pricing_plan.price,
          payment_method: 'alipay' // 默认支付宝
        };
        const payment = await createPayment(paymentData);
        
        // 处理支付（模拟支付成功）
        await processPayment(payment.id);
        
        // 更新当前订阅
        await this.fetchCurrentSubscription(true); // 强制刷新订阅信息
        
        return subscription;
      } catch (error) {
        this.error = '订阅计划失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    async cancelSubscriptionAutoRenew() {
      if (!this.currentSubscription) return;
      
      this.loading = true;
      try {
        await cancelAutoRenew(this.currentSubscription.id);
        await this.fetchCurrentSubscription(true); // 强制刷新订阅信息
      } catch (error) {
        this.error = '取消自动续订失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    async fetchPaymentHistory() {
      this.loading = true;
      try {
        const payments = await getPaymentHistory();
        this.paymentHistory = payments;
        return payments;
      } catch (error) {
        this.error = '获取支付历史失败';
        throw error;
      } finally {
        this.loading = false;
      }
    }
  }
});